package com.lahuan.config.mybatis.handlers;

import com.alibaba.fastjson.JSON;
import com.lahuan.demo.dto.StudentDetail;
import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;
import org.apache.ibatis.type.MappedJdbcTypes;
import org.apache.ibatis.type.MappedTypes;

import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;


/**
 * 数据库用字符串类型保存json字符串
 * java程序中用一个实体类接收
 * 这里是做转换的Handler
 */
// 数据库数据类型
@MappedJdbcTypes(JdbcType.VARCHAR)
// java类型
@MappedTypes(StudentDetail.class)
public class StudentDetailTypeHandler extends BaseTypeHandler<StudentDetail> {


    public StudentDetail parseObject(String jsonSource) {
        if (jsonSource != null && jsonSource.length() > 0) {
            return JSON.parseObject(jsonSource, StudentDetail.class);
        }
        return null;
    }

    @Override
    public void setNonNullParameter(PreparedStatement ps, int i, StudentDetail parameter, JdbcType jdbcType) throws SQLException {
        ps.setString(i, JSON.toJSONString(parameter));
    }

    @Override
    public StudentDetail getNullableResult(ResultSet rs, String columnName) throws SQLException {
        return parseObject(rs.getString(columnName));
    }

    @Override
    public StudentDetail getNullableResult(ResultSet rs, int columnIndex) throws SQLException {
        return parseObject(rs.getString(columnIndex));
    }

    @Override
    public StudentDetail getNullableResult(CallableStatement cs, int columnIndex) throws SQLException {
        return parseObject(cs.getString(columnIndex));
    }
}

